using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using ALib;
using AxTWSLib;
using TWSLib;
using _DTwsEvents_historicalDataEventHandler = AxTWSLib._DTwsEvents_historicalDataEventHandler;

namespace TradingPlatform.IB.Operations
{
    public class HistoricalBar
    {
        private readonly AxTws _tws;
        private UtcConverter _utcConverter;

        private readonly TickerNameAndId _tickerId;

        public readonly SortedList<string,List<string>> _result;

        public HistoricalBar(AxTws tws)
        {
            _tws = tws;
            _tws.historicalData += new _DTwsEvents_historicalDataEventHandler(_tws_historicalData);
            _tickerId = new TickerNameAndId();
            _result = new SortedList<string, List<string>>();
        }

        public void RequestHistoricalBars(int tradingPlatformTimeZoneIndex, int exchangeTimeZoneIndex,
                                          string exchange, string secType, string symbol, string expiry, string currency,
                                          DateTime endDateTimeOfTradingPlatform, TimeSpan duration, string barSize, string whatToShowType, bool useRegularTradingHours)
        {
            _utcConverter = new UtcConverter(tradingPlatformTimeZoneIndex, exchangeTimeZoneIndex);
            IContract contract = _tws.createContract();

            contract.exchange = exchange;
            contract.secType = secType;
            contract.symbol = symbol;
            contract.expiry = expiry;
            contract.currency = currency;
            contract.includeExpired = 1;

            int useRTH = useRegularTradingHours ? 1 : 0;

            string tickerName = TickerNameAndId.ToTickerName(exchange, secType, symbol, expiry, currency);
            _tickerId.Add(tickerName);
            int tickerId = _tickerId.GetId(tickerName);

            if (!_result.ContainsKey(tickerName))
            {
                _result.Add(tickerName, new List<string>());
            }
            _result[tickerName].Clear();

            _tws.reqHistoricalDataEx(tickerId, contract, endDateTimeOfTradingPlatform.ToString("yyyyMMdd HH:mm:ss"), (int)duration.TotalSeconds + " S", barSize, whatToShowType, useRTH, 1);
        }

        void _tws_historicalData(object sender, _DTwsEvents_historicalDataEvent e)
        {
            int tickerId = e.reqId;
            string tickerName = _tickerId.GetTickerName(tickerId);
            
            DateTime tradingPlatformTime = DateTimeConverter.ToDateTime(e.date.Replace("  ", " "));
            DateTime exchanDateTime = _utcConverter.TradingPlatformTimeToExchangeTime(tradingPlatformTime);
            string barString = string.Format(@"{0},{1},{2},{3},{4},{5},{6}", exchanDateTime.ToString(DateTimeFormatType.DateSimple), exchanDateTime.ToString(DateTimeFormatType.TimeComplete), e.open,e.high, e.low, e.close, e.volume);
            _result[tickerName].Add(barString);
        }
    }
}